package com.isc.udpCommunication01;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

/**
 * 1.编写一个接收端A(服务器端)和一个发送端B(客户端)
 * 2.接收端A在9999端口等待接收数据
 * 3.发送端B向接收端A发送数据"hello,明天吃火锅~"
 * 4.接收端A接收到发送端B发送的数据，回复"好的明天见",然后退出
 * 5.发送端接收回复的数据，再退出
 */
public class Client {
    public static void main(String[] args) throws IOException {
        //发送端
        //在9998端口监听
        DatagramSocket datagramSocket = new DatagramSocket(9998);

        //设置要发送的消息
        byte[] buf = "hello,明天吃火锅~".getBytes();
        int dataLength = buf.length;
        DatagramPacket datagramPacket = new DatagramPacket(buf,0,dataLength,InetAddress.getByName("127.0.0.1"),9999);
        datagramSocket.send(datagramPacket);
        System.out.println("发送消息成功~");

        //接收之前接收端回复的消息
        byte[] reply = new byte[1024];
        DatagramPacket replyPacket = new DatagramPacket(reply, reply.length);
        datagramSocket.receive(replyPacket);
        //得到数据报中的数据
        byte[] replyPacketData = replyPacket.getData();
        int replyPacketLength = replyPacket.getLength();
        System.out.println("回复的消息是:"+new String(replyPacketData,0,replyPacketLength));

        //关闭资源
        datagramSocket.close();
    }
}
